package com.ruoyi.bigScreen;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Api(tags = "验证码识别")
@RestController
@RequestMapping("/screen/reCaptcha")
public class ReCaptchaController {


    @PostMapping("/getImgReCaptcha")
    @ApiOperation("根据图片识别验证码")
    public AjaxResult getImgReCaptcha(@RequestBody String imageUrl) throws Exception {
        HttpURLConnection connection = getHttpURLConnection(imageUrl);

        // 读取响应
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            // 解析 JSON 响应
            String jsonResponse = response.toString();
        connection.disconnect();
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(jsonResponse);
        String dataValue = rootNode.get("data").get("data").asText();
        return AjaxResult.success(dataValue);
    }

    private static HttpURLConnection getHttpURLConnection(String imageUrl) throws IOException {
        String token = "NGr9o0nBFNPib7CHX5J-tvI0D7s5YwnnnjW_PpK5ypc";
        String type = "10111";

        // 构建请求 payload
        String payload = String.format("{\"image\": \"%s\", \"token\": \"%s\", \"type\": \"%s\"}", imageUrl, token, type);

        // 设置请求的 URL
        String url = "http://api.jfbym.com/api/YmServer/customApi";

        // 设置请求头
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        // 发送请求
        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.writeBytes(payload);
            wr.flush();
        }
        return connection;
    }
}
